package gpstools;

import gpstools.calc.Calculator;
import gpstools.track.TrackPoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Polyline, a list of points
 * 
 * @author Marcin Skruch
 */
public class Polyline {
    private final List<TrainingPoint> points = new ArrayList<TrainingPoint>();

    public Polyline(List<TrainingPoint> points) {
        super();
        if (points == null || points.size() < 2) {
            throw new IllegalArgumentException("polyline must have at least 2 points");
        }
        this.points.addAll(points);
    }

    public Polyline(Location[] locations) {
        super();
        if (locations == null || locations.length < 2) {
            throw new IllegalArgumentException("polyline must have at least 2 points");
        }
        for (Location location : locations) {
            add(location);
        }
    }

    private void add(Location location) {
        this.points.add(TrackPoint.builder(new Point(location)).build());
    }

    public Polyline() {
        super();
    }

    public TrainingPoint closestPointTo(Location destination) {
        Double distance = null;
        TrainingPoint nearest = null;
        for (int i = 0; i < points.size() - 1; i++) {
            TrainingPoint next = new LineSegment(points.get(i), points.get(i + 1)).closestPointTo(destination);
            double distanceToPoint = Points.distance(next, destination);
            if (distance == null || distanceToPoint < distance) {
                nearest = next;
                distance = distanceToPoint;
            }
        }
        return nearest;
    }
    
    public List<Location> findCheckpoints(int number) {
        // TODO refactor
        double totalDistance = Calculator.distance(points);
        Location[] checkPoints = new Location[number];
        double[] checkDistances = new double[number];
        for (int i = 0; i < checkDistances.length; i++) {
            checkDistances[i] = ((double) (i + 1)) * totalDistance / (number + 1);
        }

        int index = 0; /* checkDistances */
        double dist = 0;
        for (int i = 1; i < points.size(); i++) {
            final Location prev = points.get(i - 1);
            final Location curr = points.get(i);

            dist += Points.distance(curr,prev);
            if (index < number && dist >= checkDistances[index]) {
                checkPoints[index] = curr;
                index++;
            }
        }
        return Arrays.asList(checkPoints);

    }


}
